import React, { useState, useEffect } from 'react';
import { Layout, Tabs, Button, Space, message, Spin, Modal } from 'antd';
import { 
  ArrowLeftOutlined, SaveOutlined, EyeOutlined, 
  SettingOutlined, UnorderedListOutlined 
} from '@ant-design/icons';
import { useNavigate, useParams } from 'react-router-dom';
import { Paper, Question, PaperStatus } from '@/types/question';
import { questionService } from '@/services/questionService';
import QuestionEditPanel from './QuestionEditPanel';
import PaperSettingsPanel from './PaperSettingsPanel';
import PaperPreview from './PaperPreview';
import styles from './index.module.css';

const { Header, Content } = Layout;

const PaperEditor: React.FC = () => {
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();
  const [activeTab, setActiveTab] = useState('questions');
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [paper, setPaper] = useState<Partial<Paper>>({
    title: '未命名试卷',
    description: '',
    status: PaperStatus.DRAFT,
    is_public: false,
    duration: 120,
    total_score: 100,
    passing_score: 60,
    show_score_after_submit: true,
    show_answer_after_submit: false,
    show_analysis_after_submit: false,
    random_question_order: false,
    random_choice_order: false,
    allow_multiple_submit: false,
    max_submit_count: 1,
  });
  const [questions, setQuestions] = useState<Question[]>([]);
  const [previewVisible, setPreviewVisible] = useState(false);

  // 加载试卷数据
  useEffect(() => {
    if (id) {
      loadPaper();
    }
  }, [id]);


  const loadPaper = async () => {
    if (!id) return;
    setLoading(true);
    try {
      const response = await questionService.getPaper(Number(id));
      const paperData = response.data.data;
      setPaper(paperData);
      
      // 转换 paper_questions 为 questions
      if (paperData.paper_questions) {
        const loadedQuestions: Question[] = paperData.paper_questions.map((pq: any) => ({
          ...pq.question_detail,
          _paper_question_id: pq.id,
          _sequence: pq.sequence,
          _group_name: pq.group_name,
          _score: pq.score,
          _is_required: pq.is_required,
        }));
        setQuestions(loadedQuestions);
      }
    } catch (error) {
      message.error('加载试卷失败');
    } finally {
      setLoading(false);
    }
  };

  // 保存试卷
  const handleSave = async () => {
    if (!id) {
      message.error('试卷还未创建');
      return;
    }

    if (!paper.title || paper.title.trim() === '') {
      message.error('请输入试卷标题');
      setActiveTab('settings');
      return;
    }

    setSaving(true);
    try {
      // 构建题目关联数据
      const questionsData = questions.map((q, index) => ({
        question_id: q.id!,
        sequence: index + 1,
        group_name: (q as any)._group_name || '',
        score: (q as any)._score || 10,
        is_required: (q as any)._is_required !== false,
      }));

      const totalScore = questionsData.reduce((sum, q) => sum + q.score, 0);

      const data: any = {
        ...paper,
        title: paper.title || '未命名试卷',
        total_score: totalScore,
        questions_data: questionsData,
      };

      await questionService.updatePaper(Number(id), data);
      message.success('试卷更新成功');
    } catch (error: any) {
      message.error(error.response?.data?.message || '保存失败');
    } finally {
      setSaving(false);
    }
  };

  // 更新试卷设置
  const handlePaperSettingsChange = (settings: Partial<Paper>) => {
    setPaper({ ...paper, ...settings });
  };

  // 更新题目列表
  const handleQuestionsChange = (newQuestions: Question[]) => {
    setQuestions(newQuestions);
  };

  const tabItems = [
    {
      key: 'questions',
      label: (
        <Space>
          <UnorderedListOutlined />
          题目编辑
        </Space>
      ),
      children: (
                <QuestionEditPanel
          questions={questions}
          onChange={handleQuestionsChange}
          paper={paper}
          onPaperChange={handlePaperSettingsChange}
        />
      ),
    },
    {
      key: 'settings',
      label: (
        <Space>
          <SettingOutlined />
          问卷设置
        </Space>
      ),
      children: (
        <PaperSettingsPanel
          settings={paper}
          onChange={handlePaperSettingsChange}
        />
      ),
    },
  ];

  if (loading) {
    return <Spin tip="加载中..." size="large" className={styles.loading} />;
  }

  return (
    <Layout className={styles.editorLayout}>
      {/* 顶部工具栏 */}
      <Header className={styles.header}>
        <div className={styles.headerContent}>
          <Space>
            <Button 
              icon={<ArrowLeftOutlined />} 
              onClick={() => navigate('/admin/question/papers')}
            >
              返回
            </Button>
            <div className={styles.title}>
              {paper.title || '未命名试卷'}
            </div>
          </Space>

          <Space>
            <Button 
              icon={<EyeOutlined />}
              onClick={() => setPreviewVisible(true)}
            >
              预览
            </Button>
            <Button 
              type="primary" 
              icon={<SaveOutlined />}
              onClick={handleSave}
              loading={saving}
            >
              保存
            </Button>
          </Space>
        </div>
      </Header>

      {/* 主内容区域 */}
      <Content className={styles.content}>
        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          items={tabItems}
          className={styles.tabs}
          size="large"
        />
      </Content>

      {/* 预览模态框 */}
      <Modal
        title="试卷预览"
        open={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        footer={null}
        width="80%"
        style={{ top: 20 }}
      >
        <PaperPreview paper={paper} questions={questions} />
      </Modal>
    </Layout>
  );
};

export default PaperEditor;

